from jose import jwt
from app.core.config import settings
from fastapi import Request, HTTPException
# 获取token
def get_token(request: Request):
    token = request.headers.get('Authorization')
    if not token:
        raise HTTPException(status_code=401, detail="未提供认证信息")
    return token

# 解码
def decode_token(token: str):
    try:
        decoded_token = jwt.decode(token, settings.SECRET_KEY, algorithms=[settings.ALGORITHM])
        return decoded_token
    except Exception as e:
        raise HTTPException(status_code=401, detail=f"token解码失败：{e}")

# 编码
def encode_token(data: dict):
    return jwt.encode(data, settings.SECRET_KEY, algorithm=settings.ALGORITHM)

# 生成token
def generate_token(data: dict):
    return encode_token(data)